package com.cyx.servlet;

import com.cyx.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


public class ReadSessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        PrintWriter writer = resp.getWriter();
        if(user !=null){
            writer.println(user.toString());
            String html = "<form action=\"/s1/session2\" method=\"post\">\n" +
                    "\t<button type=\"submit\">Session失效</button>\n" +
                    "</form>";
            writer.println(html);
        }else{
            writer.println("user="+user);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        //resp.getWriter().println("OK");
        //req.getRequestDispatcher("/session2").forward(req,resp);
        resp.sendRedirect(req.getContextPath()+"/session2");
    }
}
